package com.lanchetech.user.service.impl;


import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.lanchetech.bean.dto.TenantFeatureDTO;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.vo.CustomerServiceVO;
import com.lanchetech.bean.vo.FlashSaleSpuVO;
import com.lanchetech.bean.vo.StoreDetailVO;
import com.lanchetech.bean.vo.TenantInfoVO;
import com.lanchetech.common.constants.BaseConstant;
import com.lanchetech.common.enums.DeletedEnum;
import com.lanchetech.common.enums.MsgUserStatusEnum;
import com.lanchetech.common.enums.WebConfigEnum;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.user.service.StoreService;
import com.lanchetech.user.service.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class StoreServiceImpl implements StoreService {

    @Autowired
    TenantMapper tenantMapper;

    @Autowired
    WebService webService;

    @Autowired
    MsgUserMapper msgUserMapper;

    @Autowired
    MsgMapper msgMapper;

    @Autowired
    ShopCollectionMapper shopCollectionMapper;

    @Autowired
    TenantConfigMapper tenantConfigMapper;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    MerchantMapper merchantMapper;

    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    OrderSkuMapper orderSkuMapper;

    @Autowired
    ShopAmountMapper shopAmountMapper;

    @Autowired
    IndustryMapper industryMapper;

    @Autowired
    ShopStatisticsMapper shopStatisticsMapper;

    @Autowired
    WebConfigMapper webConfigMapper;

    @Autowired
    SpuMapper spuMapper;

    @Autowired
    private FlashSaleActivityMapper flashSaleActivityMapper;
    @Autowired
    private FlashSaleSpuMapper flashSaleSpuMapper;

    @Override
    public ResultData<StoreDetailVO> getStoreDetail(User user, Long tenantId) {
        //更新商店统计数据
        shopStatisticsMapper.updateVisitCountByShopId(tenantId);

        StoreDetailVO vo = new StoreDetailVO();
        Tenant tenant = tenantMapper.selectByPrimaryKey(tenantId);
        Shop shop = shopMapper.selectByPrimaryKey(tenantId);

        TenantInfoVO info = shopMapper.getTenantInfoById(tenantId);
        if (tenant != null) {
            info.setMerchantId(tenant.getMerchantId());
            info.setFeature(tenant.getFeature());
            info.setImageUrl(tenant.getImageUrl());
            info.setDescription(tenant.getDescription());

            TenantFeatureDTO dto = JSON.parseObject(tenant.getFeature(), TenantFeatureDTO.class);
            if (dto != null && dto.getRecommendCustomPageId() != null) {
                vo.setRecommendCustomPage(webService.getCustomPageDetail(dto.getRecommendCustomPageId()).getValue());
            }
        }
        info.setTenantName(shop.getShopName());
        info.setTenantNickname(shop.getShopName());
        info.setServiceStar(Double.valueOf(shop.getServiceStar().toString()));
        info.setEnvironmentStar(Double.valueOf(shop.getEnvironmentStar().toString()));
        info.setValueStar(shop.getValueStar().doubleValue());
        info.setSpuNumber(spuMapper.countByTenantId(shop.getId()));
        info.setShopLevel(shop.getShopLevel());
        vo.setTenantInfoVO(info);



        if (user != null) {
            ShopCollection shopCollection = shopCollectionMapper.findOneByShopIdAndUserId(tenantId, user.getId());
            vo.setHasFollowed(shopCollection != null);
        }

        vo.setFansCount(shopCollectionMapper.countByShopId(tenantId));
        vo.setTotalSales(orderSkuMapper.sumCountByTenantId(tenantId));
        vo.setTagSearch(webConfigMapper.findValueByName(WebConfigEnum.TAG_SEARCH.getConfig()));

        ShopAmount shopAmount = shopAmountMapper.findOneByShopId(tenantId);
        if (shopAmount != null) {
            Long sameTotalRank = shopAmountMapper.countByAmountGreaterThanAndIndustryFirstId(shopAmount.getAmount(), shopAmount.getIndustryFirstId()) + 1;
            if (sameTotalRank < 4) {
                Industry industry = industryMapper.selectByPrimaryKey(shopAmount.getIndustryFirstId());
                vo.setRankRemark(industry.getName() + "排行榜：TOP" + sameTotalRank);
            }
        }

        vo.setCertificateList(shop.getCertificateList());
        List<CustomerServiceVO> tenantCustomerService = msgUserMapper.getTenantCustomerService(tenantId);
        vo.setAfterSalePhone(shop.getAfterSalePhone() != null ? shop.getAfterSalePhone() : shop.getPhone());
        vo.setCustomerServices(tenantCustomerService);

        //店铺简介
        vo.setImageList(shop.getImageList());
        if(tenant != null){
            vo.setVideoUrl(tenant.getVideoUrl());
            vo.setContent(tenant.getContent());
        }

        // 如果店铺没有参与秒杀活动 则状态为0 不展示
        vo.setActivityRankStatus(BaseConstant.ZERO);
        List<FlashSaleActivity> allStartActivity = flashSaleActivityMapper.findAllStartActivity(new Date());
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(allStartActivity)) {
            List<Long> ids = allStartActivity.stream().map(FlashSaleActivity::getId).collect(Collectors.toList());
            List<FlashSaleSpuVO> flashSpu = flashSaleSpuMapper.findAllByActivityIdsAndTenantId(ids, tenantId);
            if (flashSpu.size() > BaseConstant.ZERO) {
                vo.setActivityRankStatus(BaseConstant.ONE);
            }
        }

        return new ResultData<>(vo);
    }

    @Override
    public ResultData<MsgUser> getStoreMsgUser(Long tenantId, Long msgUserId) {

        // 获取商家正在服务中的客服
        List<MsgUser> list = msgUserMapper.findAllByTenantIdAndStatusAndDeleted(tenantId, MsgUserStatusEnum.IN_SERVICE.getStatus(), DeletedEnum.DEFAULT.getStatus());

        if (!CollectionUtils.isEmpty(list)) {

            // 获取最近1次沟通的消息
            Msg msg = msgMapper.findOneLastByTenantIdAndFromId(tenantId, msgUserId);
            // 如果沟通过，并且还在3天内
            if (msg != null && msg.getCreatedAt().getTime() + 3 * 86400 * 1000 > System.currentTimeMillis()) {
                Optional<MsgUser> msgUserOptional = list.parallelStream().filter(s -> s.getId().equals(msg.getToId())).findFirst();
                // 如果在线
                if (msgUserOptional.isPresent()) {
                    MsgUser msgUser = msgUserOptional.get();
                    msgUser.setPassword(null);
                    return new ResultData<>(msgUser);
                }
            }


            // 随机选择1个客服
            Random r = new Random();
            MsgUser msgUser = list.get(r.nextInt(list.size()));
            msgUser.setPassword(null);
            return new ResultData<>(msgUser);
        }
        return new ResultData<>(null);
    }

    @Override
    public ResultData<TenantConfig> getTenantConfig(Long tenantId, String name) {
        return new ResultData<>(tenantConfigMapper.findOneByTenantIdAndName(tenantId, name));
    }
}